package com.dongdong.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayConfig;
import com.alipay.api.internal.util.AlipaySignature;
import com.dongdong.api.ItemApi;
import com.dongdong.api.OrderApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Controller
@RequestMapping("/ny")
public class NotifyUrlAndReturnUrlController {


    @Autowired
    private OrderApi orderApi;


    @Value("${aliPay.charset}")
    private String charset;

    @Value("${aliPay.alipayPublicKey}")
    private String alipayPublicKey;

    @Value("${aliPay.signType}")
    private String signType;

    //get
    @GetMapping(value = "/returnUrl")
    public String getReturnUrl(HttpServletRequest request, Model model, String out_trade_no, String trade_no, String total_amount){

        //获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            params.put(name, valueStr);
        }
        //验签
        boolean signVerified = false; //调用SDK验证签名
        try {
            signVerified = AlipaySignature.rsaCheckV1(params, alipayPublicKey, charset, signType);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }

        //——请在这里编写您的程序（以下代码仅作参考）——
        if(signVerified) {
            //商户订单号
            System.out.println(out_trade_no);
            //支付宝交易号
            System.out.println(trade_no);
            //付款金额
            System.out.println(total_amount);

            System.out.println("trade_no:"+trade_no+"<br/>out_trade_no:"+out_trade_no+"<br/>total_amount:"+total_amount);

            model.addAttribute("out_trade_no",out_trade_no);
            model.addAttribute("trade_no",trade_no);
            model.addAttribute("total_amount",total_amount);
            return "paysuccess";  //跳转paysuccess页面

        }else {
            System.out.println("验签失败");
            return "payfail";  //跳转paysuccess页面

        }

    }





    //post
    @PostMapping(value = "/notifyUrl")
    public String notifyUrl(HttpServletRequest request, String out_trade_no, String trade_no, String trade_status) {

        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            params.put(name, valueStr);
        }


        boolean signVerified = false; //调用SDK验证签名
        try {
                signVerified = AlipaySignature.rsaCheckV1(params,alipayPublicKey, charset, signType);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }

        //——请在这里编写您的程序（以下代码仅作参考）——

        if(signVerified) {//验证成功

            if(trade_status.equals("TRADE_FINISHED")){

            }else if (trade_status.equals("TRADE_SUCCESS")){  //交易成功
                 //支付成功 （作业）
                // 更改订单状态 order表
                // 根据订单编号更新支付宝支付成功流水号   tb_order_item表

                orderApi.updateOrder(out_trade_no,trade_no,trade_status); //修改

                System.out.println("------------------------------------------->>>>>>>>>");

            }

            System.out.println("success");
            return "success";

        }else {//验证失败
            System.out.println("fail");
            return "fail";
        }

    }










    }
